package com.dyz.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.dyz.model.WebLog;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;

@Component
@Aspect
@Order(1)
@Slf4j
public class WebLogAspect {

    /**
     * 日志记录
     * 环绕通知，方法执行之前和之后执行
     */

    /**
     * 定义切入点
     */
    @Pointcut("execution(public * com.dyz.controller.*.*(..))")// 所有controller包下的所有方法
    public void webLog() {

    }
    /**
     * 记录日志的环绕通知
     */
    @Around("webLog()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result=null;
        WebLog webLog = new WebLog();
        long start=System.currentTimeMillis();
        result= joinPoint.proceed(joinPoint.getArgs());
        long end=System.currentTimeMillis();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取安全上下文
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        webLog.setSpendTime((long)(end-start)/1000);
        String url = request.getRequestURL().toString();
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(url);
        webLog.setIp(request.getRemoteAddr());
        webLog.setBasePath(StrUtil.removeSuffix(url, URLUtil.url(url).getPath()));
        webLog.setUsername(authentication==null?"anonymous":authentication.getPrincipal().toString());
        webLog.setIp(request.getRemoteAddr());//TODO 获取用户真实IP
        //因为要使用swagger工具，必须在方法上添加@ApiOperation注解
        //获取方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取类名
        String className = joinPoint.getTarget().getClass().getName();
        Method method = signature.getMethod();
        webLog.setResult(result);
        //获取Operations
        ApiOperation annotation = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(annotation==null?"no desc":annotation.value());
        webLog.setMethod(className+"."+method.getName());
        webLog.setParameter(getModeParameter(method,joinPoint.getArgs()));
        log.info("{}", JSON.toJSONString(webLog,true));
        return result;
    }

    /**
     * 获取方法的参数
     * @param method
     * @return
     */
    private Object getModeParameter(Method method, Object[] args) {
        HashMap<String, Object> methodParameter = new HashMap<>();
        LocalVariableTableParameterNameDiscoverer nameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
        //获取参数名称
        String[] parameterNames = nameDiscoverer.getParameterNames(method);
        for (int i = 0; i < parameterNames.length; i++) {
            methodParameter.put(parameterNames[i],args[i]);
        }
        return methodParameter;
    }
}
